<template>
  <div class="app-container">
    <el-form :inline="true" :model="queryParams" ref="queryRef" label-width="80px">
      <el-form-item label="学员">
        <el-select v-model="queryParams.studentId" filterable remote clearable placeholder="选择学员"
          :remote-method="searchStudents" :loading="loadingStudents" style="width:220px" @visible-change="onStudentVisible">
          <el-option v-for="s in studentOptions" :key="s.studentId" :label="s.name + '（' + s.studentNo + '）'" :value="s.studentId" />
        </el-select>
      </el-form-item>
      <el-form-item label="科目">
        <el-select v-model="queryParams.subjectId" filterable remote clearable placeholder="选择科目"
          :remote-method="searchSubjects" :loading="loadingSubjects" style="width:220px" @visible-change="onSubjectVisible">
          <el-option v-for="sub in subjectOptions" :key="sub.subjectId" :label="sub.subjectName" :value="sub.subjectId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option label="未开始" value="未开始" />
          <el-option label="学习中" value="学习中" />
          <el-option label="完成" value="完成" />
          <el-option label="不合格" value="不合格" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['jiaxiao:progress:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['jiaxiao:progress:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete()" v-hasPermi="['jiaxiao:progress:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" :row-key="getRowId">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="progressId" width="100" />
      <el-table-column label="学员" prop="studentId" width="160" :formatter="fmtStudent" />
      <el-table-column label="科目" prop="subjectId" width="140" :formatter="fmtSubject" />
      <el-table-column label="教练" prop="assignedInstructorId" width="160" :formatter="fmtInstructor" />
      <el-table-column label="累计学时" prop="hoursTotal" width="120" />
      <el-table-column label="要求学时" prop="hoursRequired" width="120" />
      <el-table-column label="状态" prop="status" width="120" />
      <el-table-column label="操作" fixed="right" width="320">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['jiaxiao:progress:edit']">修改</el-button>
          <el-button size="mini" type="text" @click="handleAddHours(scope.row)">加时</el-button>
          <el-button size="mini" type="text" @click="handleViewExams(scope.row)">考试记录</el-button>
          <el-button size="mini" type="text" @click="handleViewRetakes(scope.row)">补考安排</el-button>
          <el-button size="mini" type="text" class="text-danger" @click="handleDelete(scope.row)" v-hasPermi="['jiaxiao:progress:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="formRef" :model="form" label-width="120px">
        <el-form-item label="学员">
          <el-select v-model="form.studentId" filterable remote clearable placeholder="选择学员"
            :remote-method="searchStudents" :loading="loadingStudents" style="width:100%" @visible-change="onStudentVisible">
            <el-option v-for="s in studentOptions" :key="s.studentId + '_f'" :label="s.name + '（' + s.studentNo + '）'" :value="s.studentId" />
          </el-select>
        </el-form-item>
        <el-form-item label="科目">
          <el-select v-model="form.subjectId" filterable remote clearable placeholder="选择科目"
            :remote-method="searchSubjects" :loading="loadingSubjects" style="width:100%" @visible-change="onSubjectVisible">
            <el-option v-for="sub in subjectOptions" :key="sub.subjectId + '_f'" :label="sub.subjectName" :value="sub.subjectId" />
          </el-select>
        </el-form-item>
        <el-form-item label="教练">
          <el-select v-model="form.assignedInstructorId" filterable remote clearable placeholder="选择教练"
            :remote-method="searchInstructors" :loading="loadingInstructors" style="width:100%" @visible-change="onInstructorVisible">
            <el-option v-for="i in instructorOptions" :key="i.staffId + '_f'" :label="i.name + '（' + i.staffNo + '）'" :value="i.staffId" />
          </el-select>
        </el-form-item>
        <el-form-item label="累计学时">
          <el-input-number v-model="form.hoursTotal" :min="0" />
        </el-form-item>
        <el-form-item label="要求学时">
          <el-input-number v-model="form.hoursRequired" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="未开始" value="未开始" />
            <el-option label="学习中" value="学习中" />
            <el-option label="完成" value="完成" />
            <el-option label="不合格" value="不合格" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open=false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </div>
    </el-dialog>

    <el-dialog title="增加学时" :visible.sync="hoursOpen" width="400px">
      <el-form :model="hoursForm" label-width="100px">
        <el-form-item label="学时增量">
          <el-input-number v-model="hoursForm.delta" :min="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hoursOpen=false">取消</el-button>
        <el-button type="primary" @click="submitAddHours">确定</el-button>
      </div>
    </el-dialog>

    <!-- 考试记录弹窗 -->
    <el-dialog title="考试记录" :visible.sync="examDialogVisible" width="800px">
      <el-table :data="examRecords" size="mini" border>
        <el-table-column prop="attemptNo" label="次数" width="60" />
        <el-table-column prop="score" label="成绩" width="80" />
        <el-table-column prop="result" label="结果" width="80">
          <template slot-scope="scope">
            <el-tag :type="getResultTagType(scope.row.result)" size="mini">
              {{ scope.row.result }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="examTime" label="考试时间" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.examTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="examDialogVisible=false">关 闭</el-button>
        <el-button type="primary" @click="handleAddExam">登记考试</el-button>
      </div>
    </el-dialog>

    <!-- 补考安排弹窗 -->
    <el-dialog title="补考安排" :visible.sync="retakeDialogVisible" width="800px">
      <el-table :data="retakeRecords" size="mini" border>
        <el-table-column prop="scheduledTime" label="安排时间" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.scheduledTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="mini">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button 
              v-if="scope.row.status === '待考试'"
              size="mini" 
              type="text" 
              @click="handleCompleteRetake(scope.row)"
            >完成</el-button>
            <el-button 
              v-if="scope.row.status === '待考试'"
              size="mini" 
              type="text" 
              @click="handleCancelRetake(scope.row)"
            >取消</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="retakeDialogVisible=false">关 闭</el-button>
        <el-button type="primary" @click="handleAddRetake">新增安排</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProgress, getProgress, addProgress, updateProgress, delProgress, addHours } from '@/api/jiaxiao/progress'
import { listStudent, getStudent } from '@/api/jiaxiao/student'
import { listSubjects } from '@/api/jiaxiao/assign'
import { listStaff, getStaff } from '@/api/jiaxiao/staff'
import { getExamRecordsByStudentAndSubject } from '@/api/jiaxiao/exam'
import { getPendingRetakesByStudent, completeRetakeSchedule, cancelRetakeSchedule } from '@/api/jiaxiao/retake'

export default {
  name: 'JxProgress',
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      single: true,
      multiple: true,
      ids: [],
      selectedRows: [],
      queryParams: { pageNum: 1, pageSize: 10, studentId: undefined, subjectId: undefined, status: undefined },
      title: '',
      open: false,
      form: {},
      hoursOpen: false,
      hoursForm: { id: undefined, delta: 1 },
      studentOptions: [],
      subjectOptions: [],
      instructorOptions: [],
      loadingStudents: false,
      loadingSubjects: false,
      loadingInstructors: false,
      studentMap: {},
      subjectMap: {},
      instructorMap: {},
      examDialogVisible: false,
      retakeDialogVisible: false,
      examRecords: [],
      retakeRecords: [],
      currentStudentId: null,
      currentSubjectId: null
    }
  },
  created() { this.getList(); this.prefetchDictionaries() },
  methods: {
    getRowId(row){ return row && (row.progressId || row.id || row.progressID || row.PROGRESS_ID) },
    getList() {
      this.loading = true
      listProgress(this.queryParams).then(res => {
        const rows = res.rows || []
        this.list = rows.map(r => ({ ...r, id: r.progressId }))
        this.total = res.total; this.loading = false
        this.buildNameMapsForList()
      })
    },
    handleQuery() { this.queryParams.pageNum = 1; this.getList() },
    resetQuery() { this.$refs.queryRef && this.$refs.queryRef.resetFields(); this.handleQuery() },
    handleSelectionChange(selection) {
      try { console.log('[progress] selection-change selection=', selection) } catch(e) {}
      this.selectedRows = selection
      this.ids = (selection||[]).map(i => this.getRowId(i)).filter(v => v !== undefined && v !== null && v !== '')
      try { console.log('[progress] mapped ids=', this.ids) } catch(e) {}
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() { this.title = '新增进度'; this.form = { hoursTotal: 0, hoursRequired: 0, status: '未开始' }; this.open = true },
    handleUpdate(row) { const id = row ? row.progressId : this.ids[0]; getProgress(id).then(({ data }) => { this.form = data; this.title = '编辑进度'; this.open = true }) },
    submitForm() { const req = this.form.progressId ? updateProgress(this.form) : addProgress(this.form); req.then(() => { this.$message.success('保存成功'); this.open = false; this.getList() }) },
    handleDelete(row) {
      try { console.log('[progress] handleDelete row=', row, 'ids(state)=', this.ids, 'selectedRows=', this.selectedRows) } catch(e) {}
      const ids = row ? [this.getRowId(row)] : (this.ids && this.ids.length ? this.ids : (this.selectedRows || []).map(r => this.getRowId(r)))
      const idsStr = (ids || []).filter(Boolean).join(',')
      try { console.log('[progress] computed idsStr=', idsStr) } catch(e) {}
      if (!idsStr) { this.$message.warning('请选择要删除的记录'); return }
      this.$modal.confirm('确认删除选中记录吗？')
        .then(() => delProgress(idsStr))
        .then(() => { this.$message.success('删除成功'); this.getList() })
    },
    handleAddHours(row) { this.hoursForm = { id: row.progressId, delta: 1 }; this.hoursOpen = true },
    submitAddHours() { addHours(this.hoursForm.id, this.hoursForm.delta).then(() => { this.$message.success('已增加学时'); this.hoursOpen = false; this.getList() }) },
    
    // 考试管理相关方法
    handleViewExams(row) {
      this.currentStudentId = row.studentId;
      this.currentSubjectId = row.subjectId;
      this.loadExamRecords();
      this.examDialogVisible = true;
    },
    loadExamRecords() {
      if (this.currentStudentId && this.currentSubjectId) {
        getExamRecordsByStudentAndSubject(this.currentStudentId, this.currentSubjectId).then(response => {
          this.examRecords = response.data || [];
        });
      }
    },
    handleViewRetakes(row) {
      this.currentStudentId = row.studentId;
      this.loadRetakeRecords();
      this.retakeDialogVisible = true;
    },
    loadRetakeRecords() {
      if (this.currentStudentId) {
        getPendingRetakesByStudent(this.currentStudentId).then(response => {
          this.retakeRecords = response.data || [];
        });
      }
    },
    handleAddExam() {
      this.$router.push('/jiaxiao/exam');
    },
    handleAddRetake() {
      this.$router.push('/jiaxiao/retake');
    },
    handleCompleteRetake(row) {
      this.$modal.confirm('确认完成这个补考安排？').then(() => {
        completeRetakeSchedule(row.retakeId).then(() => {
          this.$message.success('操作成功');
          this.loadRetakeRecords();
        });
      });
    },
    handleCancelRetake(row) {
      this.$modal.confirm('确认取消这个补考安排？').then(() => {
        cancelRetakeSchedule(row.retakeId).then(() => {
          this.$message.success('操作成功');
          this.loadRetakeRecords();
        });
      });
    },
    getResultTagType(result) {
      switch(result) {
        case '通过': return 'success';
        case '未通过': return 'danger';
        case '缺考': return 'warning';
        default: return '';
      }
    },
    getStatusTagType(status) {
      switch(status) {
        case '待考试': return 'warning';
        case '已完成': return 'success';
        case '已取消': return 'danger';
        default: return '';
      }
    },
    prefetchDictionaries(){
      // 预取全部科目，常量少
      listSubjects().then(res=>{ this.subjectOptions = res.data||[]; this.subjectMap = Object.fromEntries(this.subjectOptions.map(s=>[s.subjectId, s.subjectName])) })
    },
    async buildNameMapsForList(){
      const studentIds = Array.from(new Set((this.list||[]).map(x=>x.studentId).filter(Boolean)))
      const instructorIds = Array.from(new Set((this.list||[]).map(x=>x.assignedInstructorId).filter(Boolean)))
      // 学员
      for (const id of studentIds){
        if (!this.studentMap[id]){
          try { const { data } = await getStudent(id); if (data) this.$set(this.studentMap, id, data.name) } catch(e) {}
        }
      }
      // 教练
      for (const id of instructorIds){
        if (id && !this.instructorMap[id]){
          try { const { data } = await getStaff(id); if (data) this.$set(this.instructorMap, id, data.name) } catch(e) {}
        }
      }
    },
    // 下拉搜索与缓存
    onStudentVisible(v){ if(v && this.studentOptions.length===0) this.searchStudents('') },
    onSubjectVisible(v){ if(v && this.subjectOptions.length===0) this.searchSubjects('') },
    onInstructorVisible(v){ if(v && this.instructorOptions.length===0) this.searchInstructors('') },
    searchStudents(q){ this.loadingStudents=true; listStudent({ pageNum:1, pageSize:10, name:q }).then(res=>{ this.studentOptions=res.rows||[]; this.loadingStudents=false; this.studentMap = Object.fromEntries(this.studentOptions.map(s=>[s.studentId, s.name])); }).catch(()=>{ this.loadingStudents=false }) },
    searchSubjects(q){ this.loadingSubjects=true; listSubjects().then(res=>{ this.subjectOptions=res.data||[]; this.loadingSubjects=false; this.subjectMap = Object.fromEntries(this.subjectOptions.map(s=>[s.subjectId, s.subjectName])); }).catch(()=>{ this.loadingSubjects=false }) },
    searchInstructors(q){ this.loadingInstructors=true; listStaff({ pageNum:1, pageSize:10, name:q }).then(res=>{ this.instructorOptions=res.rows||[]; this.loadingInstructors=false; this.instructorMap = Object.fromEntries(this.instructorOptions.map(i=>[i.staffId, i.name])); }).catch(()=>{ this.loadingInstructors=false }) },
    // 表格显示格式化
    fmtStudent(row){ return this.studentMap[row.studentId] || row.studentId },
    fmtSubject(row){ return this.subjectMap[row.subjectId] || row.subjectId },
    fmtInstructor(row){ return this.instructorMap[row.assignedInstructorId] || row.assignedInstructorId }
  }
}
</script>

<style scoped>
.mb8 { margin-bottom: 8px; }
</style>


